/**
 * 
 */
package protocol;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * DataInputStream with custom receive() function to 
 * process incoming data into the protocol-defined formats.
 * 
 * To be wrapped around a socket's input stream.
 * 
 * @author WHOMP
 */
public class CtfDataInputStream extends DataInputStream {

	/**
	 * Read each portion of the incoming stream as expected
	 * and parse into a CtfPacket.
	 * 
	 * Calling function must do something based on message type.
	 * 
	 * @return CtfPacket
	 */
	public CtfPacket receive() {
		try {
			int sender = readShort();
			System.err.println( "sender: " + sender);
			
			int msgType = readShort();
			System.err.println( "msgType: " + msgType);
			
			int gameState = readInt();
			System.err.println( "gameState: " + gameState);
			int bodyLength = readInt();
			System.err.println( "bodyLength: " + bodyLength);

			CtfHeader header = new CtfHeader( sender, msgType, gameState,
										bodyLength);

			// read msg of length bodyLength
			byte[] msgBytes = new byte[bodyLength];
			System.err.println( msgBytes.length + " " + bodyLength );
			//for(int i = 0; i <bodyLength; i++)
				//msgBytes[i] = (byte) readChar();
			
			int bytesRead = read( msgBytes, 0, bodyLength );
			// throw exception if body length and header info don't match
//			if ( bytesRead != bodyLength ) {
//				//throw new IOException("Bytes read " + bytesRead + "does not equal expected body length" + bodyLength);
//				//System.out.println(new String(msgBytes));
//			}
			
			// save off byte array read
			while ( bytesRead < bodyLength ) {
				int leftToRead = bodyLength - bytesRead;
				bytesRead += read( msgBytes, bytesRead, leftToRead);
			}
			return new CtfPacket( header, msgBytes );
			
			
		} catch ( IOException e ) {
			e.printStackTrace();
		}
		
		// error
		return null;
	}
	
	/* Constructor */
	public CtfDataInputStream(InputStream arg0) {
		super(arg0);
	}

}
